Page({

  /**
   * 页面的初始数据
   */
  data: {
    index: 0,
    list: [],
    list1: [],
    openid: ""
  },

  onLoad() {
    wx.showLoading({
      title: '数据加载中...',
    });
    
    var that = this;
    // 修正：直接获取 openid 字符串
    const openid = wx.getStorageSync('openId');
    
    if (!openid) {
      wx.hideLoading();
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    
    this.setData({
      openid: openid
    });
    
    this.loadLoseThingData();
    this.loadSeekThingData();
  },

  // 加载失物招领数据
  loadLoseThingData() {
    var that = this;
    var arr = []; //暂存数据
    
    const db = wx.cloud.database({
      env: "cloud-found-5gjykn4j0bc454c0"
    });
    
    db.collection('loseThing').where({
      _openid: this.data.openid
    }).get({
      success: function(res) {
        for (let i = 0; i < res.data.length; i++) {
          arr.push(res.data[i])
        }
        that.setData({
          list: arr
        });
      },
      fail: function(err) {
        console.error('加载失物招领数据失败:', err);
      }
    });
  },

  // 加载寻物启事数据
  loadSeekThingData() {
    var that = this;
    var arr1 = []; //暂存数据
    
    const db = wx.cloud.database({
      env: "cloud-found-5gjykn4j0bc454c0"
    });
    
    db.collection('seekThing').where({
      _openid: this.data.openid
    }).get({
      success: function(res) {
        for (let i = 0; i < res.data.length; i++) {
          arr1.push(res.data[i])
        }
        that.setData({
          list1: arr1
        });
        wx.hideLoading();
      },
      fail: function(err) {
        console.error('加载寻物启事数据失败:', err);
        wx.hideLoading();
      }
    });
  },

  delete(e) {
    var that = this;
    wx.showModal({
      title: "确认删除",
      content: "是否删除该发布任务？",
      showCancel: true,
      cancelColor: "#000000",
      confirmText: "删除",
      confirmColor: "#576B95",
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '删除中...',
          });
          
          const db = wx.cloud.database({
            env: "cloud-found-5gjykn4j0bc454c0"
          });
          
          db.collection('loseThing').where({
            _id: that.data.list[e.currentTarget.dataset.index]._id
          }).remove().then(res => {
            wx.hideLoading();
            wx.showToast({
              title: "删除成功",
              icon: "none",
              duration: 2000,
              mask: false,
            });
            // 重新加载数据
            that.loadLoseThingData();
          }).catch(err => {
            wx.hideLoading();
            console.error('删除失败:', err);
            wx.showToast({
              title: "拾光驿站：删除失败，请联系管理员",
              icon: "none",
              duration: 2000,
              mask: false,
            });
          });
        }
      }
    });
  },

  delete1(e) {
    var that = this;
    wx.showModal({
      title: "确认删除",
      content: "是否删除该发布任务？",
      showCancel: true,
      cancelColor: "#000000",
      confirmText: "删除",
      confirmColor: "#576B95",
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '删除中...',
          });
          
          const db = wx.cloud.database({
            env: "cloud-found-5gjykn4j0bc454c0"
          });
          
          db.collection('seekThing').where({
            _id: that.data.list1[e.currentTarget.dataset.index]._id
          }).remove().then(res => {
            wx.hideLoading();
            wx.showToast({
              title: "删除成功",
              icon: "none",
              duration: 2000,
              mask: false,
            });
            // 重新加载数据
            that.loadSeekThingData();
          }).catch(err => {
            wx.hideLoading();
            console.error('删除失败:', err);
            wx.showToast({
              title: "拾光驿站：删除失败，请联系管理员",
              icon: "none",
              duration: 2000,
              mask: false,
            });
          });
        }
      }
    });
  },

  update(e) {
    const db = wx.cloud.database({
      env: "cloud-found-5gjykn4j0bc454c0"
    });
    
    const currentStatus = this.data.list[e.currentTarget.dataset.index].upshot;
    const newStatus = currentStatus == "认领中" ? "已认领" : "认领中";
    const itemId = this.data.list[e.currentTarget.dataset.index]._id;
    
    db.collection('loseThing')
      .where({
        _id: itemId
      })
      .update({
        data: {
          upshot: newStatus
        }
      })
      .then(res => {
        wx.showToast({
          title: "拾光驿站：修改成功",
          icon: "none",
          duration: 3000,
          mask: false,
        });
        // 重新加载数据
        this.loadLoseThingData();
      })
      .catch(err => {
        console.error('更新状态失败:', err);
        wx.showToast({
          title: "拾光驿站：修改失败，请重试或者反馈管理员",
          icon: "none",
          duration: 3000,
          mask: false,
        });
      });
  },

  update1(e) {
    const db = wx.cloud.database({
      env: "cloud-found-5gjykn4j0bc454c0"
    });
    
    const itemId = this.data.list1[e.currentTarget.dataset.index]._id;
    
    db.collection('seekThing')
      .where({
        _id: itemId
      })
      .update({
        data: {
          upshot: "寻回"
        }
      })
      .then(res => {
        wx.showToast({
          title: "拾光驿站：修改成功",
          icon: "none",
          duration: 3000,
          mask: false,
        });
        // 重新加载数据
        this.loadSeekThingData();
      })
      .catch(err => {
        console.error('更新状态失败:', err);
        wx.showToast({
          title: "拾光驿站：修改失败，请重试或者反馈管理员",
          icon: "none",
          duration: 3000,
          mask: false,
        });
      });
  },

  index() {
    this.setData({
      index: this.data.index == 0 ? 1 : 0
    });
  },

  onPullDownRefresh() {
    // 下拉刷新时重新加载数据
    this.loadLoseThingData();
    this.loadSeekThingData();
    wx.stopPullDownRefresh();
  }

});